<template>
	<view class="comment-detail-container">
		<view class="no-token-mask" v-if="!token" @click="toLogin"></view>	
		<view class="no-data-page" v-if="nodataPageShow">
			<image class="no-data-img" src="../../static/noDataIcon.png"></image>
			<text class="no-data-tips">好友还未填写评价</text>
		</view>	
		<commentItem v-if="commentData" ref="commentItem" :isInDetailPage="true" @toReply="showReplyInput" @toComment="showCommentInput" :commentDataOrigin="commentData"></commentItem>
		<replyCommentInput v-if="replyInputShow" :autoFocus="true" @blur="hideInput" @submit="submitReply" :placeholder="placeholderText"></replyCommentInput>
		<confirmPop :title="'提示'" :btns="confirmPopBtns" :content="confirmPopContent"
			@maskClk="closeConfrimPop" @btnClk="confrimPopBtnClk" v-show="confirmPopShow">
		</confirmPop>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex"
	export default {
	
		data() {
			return {
				commentData: null,
				commentId:0,
				replyInputShow: false,
				placeholderText:'我来说几句',
				friendList:[],
				confirmPopShow:false,
				confirmPopContent: '点评人申请添加你为好友',
				confirmPopBtns: [{
					text: '去添加',
					type: 'confirm'
				}, {
					text: '暂不添加',
					type: 'cancel',
					bgColor: '#E5E5E5'
				}],
				nodataPageShow:false
			}
		},
		computed: {
		  ...mapState(['fromUserId','fromVirtualId','userInfo','token'])
		},
		onLoad(options){
			this.commentId = options.id || options.virtualId
			if(options.virtualId){
				// 分享过来的点评
			    this.$store.commit('setFromVirtualId', options.virtualId)
				if(this.token){
					// 已登录过，则去拿好友信息
					this.getFriendList()
				}
			}
			if (options.fromUserId) {
				this.$store.commit('setFromUserId', options.fromUserId)
			}
			this.getCommentData(this.commentId)
		},
		onPullDownRefresh() {
			this.getCommentData(this.commentId)
		},
	
		methods:{
			getCommentData(id){
				uni.showLoading({mask: true});
				this.$api.getEvaluateDetail(id).then((res)=>{
					if(res){
                        this.commentData = res
						this.nodataPageShow = false
					}else{
						this.nodataPageShow = true
					}
					uni.hideLoading()
					uni.stopPullDownRefresh()
				}).catch(()=>{
					this.nodataPageShow = true
				})
			},
			hideInput() {
				this.replyInputShow = false
			},
			showReplyInput(data) {
				this.placeholderText = `@回复 ${data.createdUserName}：`
				this.replyToUserId = data.createdUserId
				this.replyToUserName = data.createdUserName
				this.replyInputShow = true
			},
			showCommentInput(){
				this.placeholderText = '我来说几句'
				this.replyInputShow = true
				this.replyToUserId = ''
				this.replyToUserName = ''
			},
			submitReply(content){
				const data = {
					evaluateId: this.commentId*1,
					commentContent: content
				}
				if(this.replyToUserId){
					data.replyToUserId =  this.replyToUserId
					data.replyToUserName = this.replyToUserName
				}
				this.$api.giveComment(data).then((res)=>{
					this.$refs.commentItem.refreshCommentData()
				})
			},
			toLogin(){
				uni.navigateTo({
					url: '/pages/login/index'
				})
			},
			getFriendList(){
               this.$api.getFriendList({},{
				   notJumpToLogin:true,
				   notShowErrorTips:true
				}).then((res)=>{
                    this.friendList = res
					this.handlerFromMsg()
			   }).catch((err)=>{
				   if(err.code == 401 || err.code == 403){
					    // 登录过期
					    this.$store.commit('setUserToken','')
					    uni.setStorageSync('token', '');
				   }else{
					   this.handlerFromMsg()
				   }
			   })
			},
			handlerFromMsg(){
                // 处理微信分享过来的信息
                if(this.fromVirtualId){
					this.bindVirtualId()
				}
				if(this.fromUserId){
					this.checkIfFriendsWithFromUser(this.fromUserId)
				}
			},
			bindVirtualId(){
				// 把点评id跟用户id绑定
                this.$api.setVirtualCommentIdToUser({
					evaluateId: this.fromVirtualId * 1,
                    userId: this.userInfo.id * 1
				}).then(()=>{
					this.$store.commit('setFromVirtualId', '')
				})
			},
			checkIfFriendsWithFromUser(fromUserId){
				const target = this.friendList.filter((item)=>{
                    return fromUserId == item.userId
				})
				if(!target.length){
                    // 好友列表中没有这个人,即还没加这个人
                    const userId = this.userInfo.id
				    if (fromUserId != userId ) {
						// 不是自己给自己发的
						// 去发送好友申请
				    	this.getFromUserInfo(fromUserId, userId)
				    }
				}
			},
			getFromUserInfo(fromUserId,userId) {
				this.$api.getUserInfoById(fromUserId).then((res) => {
					const data = {
						fromUserId: fromUserId * 1,
						fromType: "微信分享",
						fromDesc: `通过微信分享添加，请确认对方身份`,
						fromRemark: `${res.nickName}请求添加您为好友`,
						toUserId: userId * 1
					}
					this.$api.sendAddFriendApply(data).then(() => {
						this.$store.commit('setFromUserId', '')
						setTimeout(() => {
							this.confirmPopShow = true
						}, 5000)
					})
				})
			},
			confrimPopBtnClk(res) {
				if(res.type === 'confirm'){
					this.getMsgList()
				}
				this.closeConfrimPop()
			},
			getMsgList(){
                this.$api.getMsgList({
					pageNo: 1,
					pageSize: 10,
					keywords:""
				}).then((res) => {
					if(res.rows && res.rows.length){
						const msgItems = res.rows.filter((item)=>{
                           return item.type == 1 && item.fromUserId == this.fromUserId
						})
						if(msgItems.length){
							// 找到这条消息了 去消息详情页
						    uni.navigateTo({
						         url: `/pages/message/msgDetail?type=${msgItems[0].type}&id=${msgItems[0].id}`
					        })
							return
						}
					}
					// 其他情况去消息列表页
					uni.navigateTo({
						url: `/pages/message/index`
					})	
				}).catch(()=>{
					// 其他情况去消息列表页
					uni.navigateTo({
						url: `/pages/message/index`
					})
				})
			},
			closeConfrimPop() {
				this.confirmPopShow = false
			}
		}
		
	}
</script>

<style lang="less">
	.comment-detail-container{
		margin: 0 auto;
		width: 690rpx;
		padding-bottom: 144rpx;
		.no-token-mask{
			position: fixed;
			top: 0;
			left: 0;
			bottom: 0;
			right: 0;
			z-index: 2;
		}
		.no-data-page{
			position: fixed;
			top: 0;
			left: 0;
			bottom: 0;
			right: 0;
			padding-bottom:200rpx;
			z-index: 1;
			display: flex;
		    align-items: center;
		    justify-content: center;
		    flex-direction: column;
		    .no-data-img{
		    	width: 200rpx;
		    	height: 200rpx;
		    }
		    .no-data-tips{
                font-size: 26rpx;
                color: #999;
		    }
		}
	}
</style>
